package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.RequestAndResultCode;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.mvp.presenter.DealerPresenter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.impl.DealerPresenterImpl;
import com.bjesc_b2c.app.appraiset.mvp.view.DealerView;
import com.bjesc_b2c.app.appraiset.utils.AliYunUtils;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.SelectPhotoPop;
import com.facebook.drawee.view.SimpleDraweeView;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.util.CustomLog;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import master_bean.BasicInfoBean;
import master_bean.DealerBean;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.bjesc_b2c.app.appraiset.mvp.view.activity.FollowActivity.CAMERA_REQUEST_CODE;
import static com.bjesc_b2c.app.appraiset.mvp.view.activity.FollowActivity.CAMERA_SYSTEM_CODE;
import static com.bjesc_b2c.app.appraiset.mvp.view.activity.FollowActivity.REQUEST_CODE_CHOOSE;
import static com.bjesc_b2c.app.appraiset.utils.BitmapUtil.copyFile;
import static com.bjesc_b2c.app.appraiset.utils.TimeListUilts.getObjectKey;


/**
 * Created by yidong on 2017/8/1.
 */

public class AddDealerActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, DealerView {

    @Bind(R.id.tv_market_name)
    TextView marketNameTv;
    @Bind(R.id.edit_dealer_name)
    EditText dealerNameEdit;
    @Bind(R.id.edit_contact_name)
    EditText bossNameEdit;
    @Bind(R.id.edit_dealer_phone)
    EditText bossphoneEdit;
    @Bind(R.id.tv_title)
    TextView titleTV;
    @Bind(R.id.iv_return)
    LinearLayout returnLin;
    @Bind(R.id.deler_photo)
    SimpleDraweeView simpleDraweeView;
    @Bind(R.id.edit_floor)//楼层
            EditText dealerFloorEdit;
    @Bind(R.id.edit_house_number)//门牌号
            EditText houseNumberEdit;
    @Bind(R.id.edit_parking_spaces)//车位数
            EditText parkingSpacesEdit;
    @Bind(R.id.edit_monthly_sales)//月销量
            EditText monthlySalesEdit;
    @Bind(R.id.edit_financial)//金融渗透率
            EditText financialEdit;
    @Bind(R.id.edit_financial_channel)//现有金融渠道
            EditText financialChannelEdit;
    @Bind(R.id.edit_channel)//收车渠道
            EditText channelEdit;
    @Bind(R.id.edit_preference)//收车偏好
            EditText preferenceEdit;
    @Bind(R.id.edit_analysis)//商户分析
            EditText analysisEdit;
    @Bind(R.id.edit_remarks)//备注
            EditText remarksEdit;
    @Bind(R.id.edit_account_number)
    EditText accountNumberEdit;//收款账号
    @Bind(R.id.edit_bank_of_account)//开户行
            EditText bankAccountEdit;
    @Bind(R.id.edit_bank_of_name)//开户名
            EditText bankNameEdit;
    @Bind(R.id.tv_representative)//维护人
            TextView representativeTv;
    //单选布局
    @Bind(R.id.rg_kanche)
    RadioGroup kancheRg;
    @Bind(R.id.rg_youxin)
    RadioGroup youxinRg;

    private BasicInfoBean infoBean;
    private DealerBean dealerBean;
    private String bossName = "";          //车行联系人姓名
    private String bossPhone = ""; //车行联系人电话
    private String carVin = "";      //车牌vin
    private String dealerAddress = "";//车行详细地址
    private String carForId = "";//车行id
    private String dealerName = "";//车行名
    private String marketId = "";//车市ID
    private String floor = "";//楼层
    private String house_number = "";//门牌号
    private String car_number = "";//车位数
    private String month_sale = "";//月均销量
    private String channel = "";//现有金融渠道
    private String penetration = "";//金融渗透率
    private int kcCombine = 0;//看车是否合作
    private int yxCombine = 0;//优信是否合作
    private String car_preference = "";//收车偏好
    private String car_channel = "";//收车渠道
    private String merchant_analysis = "";//商户分析
    private String description = "";//备注
    private String dealerID;
    private String accountNumber;//收款账号
    private String bankName;
    private String bankAccount;
    private DealerPresenter presenter;
    private boolean isEdit = false;
    private String filePath;
    private String fileName;
    private SelectPhotoPop photoPop;
    private String salesId;//维护人ID
    private String photoPath;
    private  Uri uri;

    @Override
    protected int getLayout() {
        return R.layout.activity_add_dealer;
    }

    @Override
    protected void initEventAndData() {
        photoPop = new SelectPhotoPop(this, popListener);
        titleTV.setText(getIntent().getStringExtra("Title"));
        isEdit = getIntent().getBooleanExtra("Edit", false);
        returnLin.setVisibility(View.VISIBLE);
        kancheRg.setOnCheckedChangeListener(this);
        youxinRg.setOnCheckedChangeListener(this);
        dealerID = getIntent().getStringExtra("carFofId");
    }

    @Override
    protected void createPresenter() {
        presenter = new DealerPresenterImpl(this);
        if (!TextUtils.isEmpty(dealerID)) {
            presenter.getDealerinfo(this, dealerID);
        }
    }

    private void getAllEditText() {
        dealerName = dealerNameEdit.getText().toString();
        bossName = bossNameEdit.getText().toString();
        bossPhone = bossphoneEdit.getText().toString();
        floor = dealerFloorEdit.getText().toString();//楼层
        house_number = houseNumberEdit.getText().toString();//门牌号
        car_number = parkingSpacesEdit.getText().toString();//车位数
        month_sale = monthlySalesEdit.getText().toString();//月均销量
        channel = financialChannelEdit.getText().toString();//现有金融渠道
        penetration = financialEdit.getText().toString();//金融渗透率
        car_preference = preferenceEdit.getText().toString();//收车偏好
        car_channel = channelEdit.getText().toString();//收车渠道
        merchant_analysis = analysisEdit.getText().toString();//商户分析
        description = remarksEdit.getText().toString();//备注
        bankName = bankNameEdit.getText().toString();
        bankAccount = bankAccountEdit.getText().toString();
        accountNumber = accountNumberEdit.getText().toString();
    }

    private DealerBean setDealer() {
        getAllEditText();
        if (dealerBean == null) {
            dealerBean = new DealerBean();
        }
        if (!TextUtils.isEmpty(dealerID))
            dealerBean.setId(dealerID);
        dealerBean.setDealer_name(dealerName);
        dealerBean.setBoss(bossName);
        dealerBean.setPhone(bossPhone);
        dealerBean.setAddress(dealerAddress);
        dealerBean.setXin_che(yxCombine);
        dealerBean.setKan_che(kcCombine);
        dealerBean.setMarket_id(marketId);
        dealerBean.setFloor(floor);
        dealerBean.setHouse_number(house_number);
        dealerBean.setCar_number(car_number);
        dealerBean.setMonth_sale(month_sale);
        dealerBean.setFinancial_penetration(penetration);
        dealerBean.setFinancial_channel(channel);
        dealerBean.setCar_channel(car_channel);
        dealerBean.setCar_preference(car_preference);
        dealerBean.setMerchant_analysis(merchant_analysis);
        dealerBean.setDescription(description);
        dealerBean.setBusiness_agent(salesId);
        dealerBean.setBank_name(bankName);
        dealerBean.setBank_deposit(bankAccount);
        dealerBean.setAccount_number(accountNumber);
        dealerBean.setDealer_photo(fileName);
        return dealerBean;
    }

    @OnClick({R.id.tv_add_dealer, R.id.rela_market_layout, R.id.iv_return, R.id.deler_photo, R.id.maintenance_person})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rela_market_layout://选择车市
                Intent intent = new Intent(AddDealerActivity.this, MarketActivity.class);
                intent.putExtra("TYPE", 1);
                startIntent(intent, RequestAndResultCode.BasicActivity_To_SelectColorActivity);
                break;
            case R.id.tv_add_dealer:
                setDealer();
//                business_agent 否 int 业务代表，现在默认当前业务员
                if (!TextUtils.isEmpty(filePath)) {
                    AliYunUtils.aLiYunUpLoadDealerImage(AddDealerActivity.this, fileName, filePath, dealerID, aliyunListener);
                }
                if (isEdit) {
                    presenter.editDealer(AddDealerActivity.this, dealerBean);
                } else {
                    presenter.addDealer(AddDealerActivity.this, dealerBean);
                }
                break;
            case R.id.iv_return:
                finish();
                break;
            case R.id.deler_photo:
                photoPop.showAtLocation(findViewById(R.id.liner_root), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.maintenance_person:
                Intent intents = new Intent(AddDealerActivity.this, SalesStaffActivity.class);
                startIntent(intents, RequestAndResultCode.BasicActivity_To_SelectColorActivity);
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (group.getId()) {
            case R.id.rg_kanche:
                kancheCheck(checkedId);
                break;
            case R.id.rg_youxin:
                youxinCheck(checkedId);
                break;
        }
    }

    private void kancheCheck(int checkedId) {
        switch (checkedId) {
            case R.id.rbtn_kx_yes:
                kcCombine = 2;
                break;
            case R.id.rbtn_kx_no:
                kcCombine = 1;
                break;
        }
    }

    private void youxinCheck(int checkedId) {
        switch (checkedId) {
            case R.id.rbtn_yx_yes:
                yxCombine = 2;
                break;
            case R.id.rbtn_yx_no:
                yxCombine = 1;
                break;
        }

    }

    @Override
    public void loadStart() {
        showLoading();
    }

    @Override
    public void loadCompleted() {
        cancelLoading();
    }

    @Override
    public void loadFailure() {

    }

    @Override
    public void getDealerInfo(DealerBean bean) {
        if (bean != null) {
            dealerNameEdit.setText(bean.getDealer_name());
            bossNameEdit.setText(bean.getBoss());
            bossphoneEdit.setText(bean.getPhone());
            dealerFloorEdit.setText(bean.getFloor());
            houseNumberEdit.setText(bean.getHouse_number());
            parkingSpacesEdit.setText(bean.getCar_number());
            monthlySalesEdit.setText(bean.getMonth_sale());
            financialChannelEdit.setText(bean.getFinancial_channel());
            financialEdit.setText(bean.getFinancial_penetration());
            preferenceEdit.setText(bean.getCar_preference());
            channelEdit.setText(bean.getCar_channel());
            analysisEdit.setText(bean.getMerchant_analysis());
            remarksEdit.setText(bean.getDescription());
            accountNumberEdit.setText(bean.getAccount_number());
            bankAccountEdit.setText(bean.getBank_deposit());
            bankNameEdit.setText(bean.getBank_name());
            representativeTv.setText(bean.getAgent_nickname());
            salesId = bean.getBusiness_agent();
            kcCombine = bean.getKan_che();
            if (kcCombine == 2) {
                ((RadioButton) kancheRg.getChildAt(0)).setChecked(true);
            } else if (kcCombine == 1) {
                ((RadioButton) kancheRg.getChildAt(1)).setChecked(true);
            }
            yxCombine = bean.getXin_che();

            if (yxCombine == 2) {
                ((RadioButton) youxinRg.getChildAt(0)).setChecked(true);
            } else if (yxCombine == 1) {
                ((RadioButton) youxinRg.getChildAt(1)).setChecked(true);
            }
            marketId = bean.getMarket_id();
            marketNameTv.setText(bean.getMarket_name());
            dealerID = bean.getId();
            if (!TextUtils.isEmpty(bean.getDealer_photo())) {
                simpleDraweeView.setImageURI(bean.getDealer_photo());
            }
        }
    }

    private View.OnClickListener popListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.rlty_select_camera:     //选择相机
                    checkPremission();
                    break;
                case R.id.rlty_select_album:    //选择相册
                    Matisse.from(AddDealerActivity.this)
                            .choose(MimeType.ofImage())
                            .countable(true)
                            .maxSelectable(1)
                            .gridExpectedSize(
                                    getResources().getDimensionPixelSize(R.dimen.dimen_120))
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                            .thumbnailScale(0.85f)
                            .imageEngine(new GlideEngine())
                            .forResult(REQUEST_CODE_CHOOSE);
                    break;
            }
            if (photoPop.isShowing()) {
                photoPop.dismiss();
            }
        }
    };

    private void checkPremission() {
        final String permission = Manifest.permission.CAMERA;  //相机权限
        final String permission1 = Manifest.permission.WRITE_EXTERNAL_STORAGE; //写入数据权限
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, permission1) != PackageManager.PERMISSION_GRANTED) {  //先判断是否被赋予权限，没有则申请权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {  //给出权限申请说明
                ActivityCompat.requestPermissions(AddDealerActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_REQUEST_CODE);
            } else { //直接申请权限
                ActivityCompat.requestPermissions(AddDealerActivity.this, new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST_CODE); //申请权限，可同时申请多个权限，并根据用户是否赋予权限进行判断
            }
        } else {  //赋予过权限，则直接调用相机拍照
            openCamera();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {  //申请权限的返回值
            case CAMERA_REQUEST_CODE:
                int length = grantResults.length;
                final boolean isGranted = length >= 1 && PackageManager.PERMISSION_GRANTED == grantResults[length - 1];
                if (isGranted) {  //如果用户赋予权限，则调用相机
                    camera();
                } else { //未赋予权限，则做出对应提示
                    showToast("打开相机失败，没有权限");
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void openCamera() {  //调用相机拍照
        Intent intent = new Intent();
        fileName = getObjectKey() + ".jpg";
        photoPath = Environment.getExternalStorageDirectory() + "/pinggushi/" + fileName;
         uri = Uri.fromFile(new File(photoPath));
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, CAMERA_SYSTEM_CODE);//启动拍照
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RequestAndResultCode.SelectColorActivity_ResultCode) {
            marketNameTv.setText(data.getStringExtra("marketName"));
            marketId = data.getStringExtra("marketId");
        } else if (resultCode == RequestAndResultCode.BasicActivityToSelectCarBrandActivity) {
            representativeTv.setText(data.getStringExtra("salesName"));
            salesId = data.getStringExtra("salesId");
        } else if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            if (data != null) {
                List<Uri> mSelected = Matisse.obtainResult(data);
                Uri selectedImage = mSelected.get(0);
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePathColumns[0]);
                String imagePath = c.getString(columnIndex);
                c.close();
                final File file1Path = new File(imagePath);
                Luban.with(this)
                        .load(file1Path)

                        .setCompressListener(new OnCompressListener() { //设置回调
                            @Override
                            public void onStart() {
                                Logger.d("压缩");
                            }
                            @Override
                            public void onSuccess(File file) {
                                Logger.d("压缩完成++" + file.getAbsolutePath());
                                copyFile(file, file1Path, true);
                            }
                            @Override
                            public void onError(Throwable e) {
                            }
                        }).launch();    //启动压缩
                filePath = imagePath;
                fileName = getObjectKey() + ".jpg";
                Logger.d("filePath--" + filePath);
                simpleDraweeView.setImageURI(selectedImage);
            }
        } else if (requestCode == CAMERA_SYSTEM_CODE && resultCode == RESULT_OK) {
            Logger.d("requestCode==");
            Logger.d("photoPath=="+photoPath);
                if (!TextUtils.isEmpty(photoPath)) {
//                    Bitmap bm = BitmapFactory.decodeFile(photoPath);
//                    Logger.d("Bitmap=="+bm.getHeight());
//                    Logger.d("Bitmap=="+bm.getWidth());
                    filePath = photoPath;
                    simpleDraweeView.setImageURI(Uri.fromFile(new File(photoPath)));
                    final File file1Path = new File(photoPath);
                    Luban.with(this)
                            .load(file1Path)                 //传人要压缩的图片//设定压缩档次，默认三挡
                            .setCompressListener(new OnCompressListener() { //设置回调
                                @Override
                                public void onStart() {
                                    // TODO 压缩开始前调用，可以在方法内启动 loading UI
                                    Logger.d("压缩");
                                }
                                @Override
                                public void onSuccess(File file) {
                                    Logger.d("压缩完成++" + file.getAbsolutePath());
                                    copyFile(file, file1Path, true);
                                    // TODO 压缩成功后调用，返回压缩后的图片文件
                                }
                                @Override
                                public void onError(Throwable e) {
                                    // TODO 当压缩过去出现问题时调用
                                }
                            }).launch();    //启动压缩
            }
        }
    }

    private AliYunUtils.OnALiYunUpLoadListener aliyunListener = new AliYunUtils.OnALiYunUpLoadListener() {
        @Override
        public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
            CustomLog.d("上传进度 =" + ((currentSize * 100) / totalSize) + "%");
        }

        @Override
        public void onSuccess(PutObjectRequest request, PutObjectResult result) {
            CustomLog.d("上传成功 = " + request.getObjectKey());
        }

        @Override
        public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
            CustomLog.d("上传失败 = " + request.getObjectKey());
        }
    };
    public void camera() {
        Intent intent = new Intent();
        fileName = getObjectKey() + ".jpg";
        photoPath = Environment.getExternalStorageDirectory() + "/pinggushi/" + fileName;
//        uri = Uri.fromFile(new File(photoPath));
//        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//        startActivityForResult(intent, CAMERA_SYSTEM_CODE);//启动拍照
//            File file = new File(photoPath);
        Uri pictureUri;
        File pictureFile = new File(photoPath);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, pictureFile.getAbsolutePath());
            pictureUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
        }else {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            pictureUri = Uri.fromFile(pictureFile);
        }
        if (intent != null) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    pictureUri);
            startActivityForResult(intent, 1);
        }

    }
}
